var fs = require('fs');
var path = require('path');
var sha1 = require('sha1');
var express = require('express');
var router = express.Router();

var User = require('../lib/mongo').User;
var checkNotLogin = require('../middlewares/check').checkNotLogin;

// POST /signup 用户注册
router.post('/', checkNotLogin,function(req, res, next) {
  var userName = req.fields.userName;
  var nickName = req.fields.nickName;
  var email = req.fields.email;
  // var avatar = req.files.avatar.path.split(path.sep).pop();
  var avatar = req.fields.avatar;
  var gender = req.fields.gender;
  var bio = req.fields.bio;
  var password = req.fields.password;
  // 明文密码加密
  password = sha1(password);

  // 待写入数据库的用户信息
  var user = {
	userName: userName,
	nickName: nickName,
	password:password,
	email: email,
	avatar: avatar,
	gender: gender,
	bio:bio
	
  };
  // 用户信息写入数据库
  User.create(user)
    .then(function (result) {
      // 此 user 是插入 mongodb 后的值，包含 _id
      user = result;
      // 将用户信息存入 session
      delete user.password;
      req.session.user = user;
      res.send(user);
    })
    .catch(function (e) {
      // 注册失败，异步删除上传的头像
      // fs.unlink(req.files.avatar.path);
      // 用户名被占用则跳回注册页，而不是错误页
      if (e.message.match('E11000 duplicate key')) {
        res.send({error:'用户名已被占用'});
        return;
      }
      next(e);
    });
});

module.exports = router;
